package br.com.lh.urabuilder.view.arrow
{
	import br.com.lh.urabuilder.util.BorderDrawer;
	import br.com.lh.urabuilder.util.pointchooser.IPointChooser;
	import br.com.lh.urabuilder.util.pointchooser.OneComponentPointChooser;
	import br.com.lh.urabuilder.util.pointchooser.TwoComponentPointChooser;
	import br.com.lh.urabuilder.view.ActionComponent;
	
	import flash.geom.Point;
	
	import mx.binding.utils.BindingUtils;
	import mx.binding.utils.ChangeWatcher;

	public class ArrowBinderDecorator
	{
		private var _arrowContainer:ArrowContainer;
		private var changeWatcherArray:Array = new Array();
		private var bindingArrow:Boolean = false;
		private var pointChooser:IPointChooser;
		

		public function ArrowBinderDecorator(arrowContainer:ArrowContainer){
			this._arrowContainer = arrowContainer;
		}

		public function bindStartComponent(element:ActionComponent):void{
			bindingArrow = true;
			changeWatcherArray.push(BindingUtils.bindSetter(componentChanged,element,"x",true));
			changeWatcherArray.push(BindingUtils.bindSetter(componentChanged,element,"y",true));
			bindingArrow = false;
			if (arrowContainer.endComponent ==null){
				pointChooser = new OneComponentPointChooser(element,arrowContainer.endPoint);
			}
			else{
				pointChooser = new TwoComponentPointChooser(element,arrowContainer.endComponent);
			}
		}

		public function bindEndComponent(element:ActionComponent):void{
			bindingArrow = true;
			changeWatcherArray.push(BindingUtils.bindSetter(componentChanged,element,"x",true));
			changeWatcherArray.push(BindingUtils.bindSetter(componentChanged,element,"y",true));
			bindingArrow = false;
			if (arrowContainer.startComponent ==null){
				pointChooser = new OneComponentPointChooser(element,arrowContainer.startPoint);
			}
			else{
				pointChooser = new TwoComponentPointChooser(arrowContainer.startComponent,element);
			}
			
		}
		
		public function componentChanged(newStartComponentXValue:Number):void{
			if (bindingArrow){
				return;
			}
			var pointArray:Array = pointChooser.pointArray;
			redrawArrow(pointArray[0],pointArray[1]);
		}
		private function redrawArrow(startPoint:Point,endPoint:Point):void{
			if (bindingArrow){
				return;
			}
			this.arrowContainer.removeWrapper();
			BorderDrawer.drawBorder(arrowContainer, arrowContainer.selected);
			this.arrowContainer.doDraw(startPoint,endPoint);
		}

		public function removeAllBindings():void{
			for each (var watcher:ChangeWatcher in changeWatcherArray){
				watcher.unwatch();
			}
		}

		public function get arrowContainer():ArrowContainer{
			return this._arrowContainer;
		}


	}
}
